<template>
  <section class="fd-base-box">
    <div class="base-setting-panel">
      <a-form
        ref="formRef"
        v-if="flowDef"
        :rules="rules"
        :model="flowDef"
        layout="vertical"
        :style="{ width: '600px' }"
      >
        <a-form-item field="icon" label="图标" required>
          <div class="icon-select-box">
            <flow-icon :icon="flowDef.icon" />
            <!-- <img :src="ICON_BASE_URL + flowDef.icon" /> -->
            <a-popover
              :show-arrow="false"
              trigger="click"
              position="rt"
              animation-name="slide-fade"
              content-class="palette-select-box"
            >
              <a-link>修改</a-link>
              <template #content>
                <div class="palette-tab">
                  <a-radio-group type="button" :default-value="0" size="large">
                    <a-radio :value="0">选择流程图标</a-radio>
                  </a-radio-group>
                </div>
                <div class="palette-main">
                  <!-- <a-card class="fonts-box" hoverable>
                    <span v-for="font in fonts">
                      <span class="flowiconfont" v-html="font" @click="handleFontClick(font)"></span>
                    </span>
                  </a-card>
                  <Sketch v-model="colors" /> -->
                  <div
                    class="icon-item"
                    v-for="(icon, idx) in icons"
                    :key="idx"
                    @click="onIconChoosed(icon)"
                  >
                    <flow-icon :icon="icon" />
                  </div>
                </div>
              </template>
            </a-popover>
          </div>
        </a-form-item>
        <a-form-item field="name" label="名称">
          <a-input v-model="flowDef.name" :max-length="16" />
        </a-form-item>
        <a-form-item field="key" label="标识">
          <a-input v-model="flowDef.key" placeholder="设置唯一的模型标识" />
        </a-form-item>
        <a-form-item field="groupId" label="分组">
          <div class="group-box">
            <a-select
              class="group-select"
              v-model="flowDef.groupId"
              placeholder="选择流程分组"
              allow-search
              @change="groupChange"
            >
              <a-option
                v-for="(group, gIdx) in groups"
                :key="gIdx"
                :value="group.id"
                :label="group.name"
              ></a-option>
            </a-select>
            <!-- <a-button class="new-group-btn" type="primary" @click="handleOpenAddGroup()">
              新增分组
              <template #icon>
                <icon-plus />
              </template>
            </a-button> -->
          </div>
        </a-form-item>
        <a-form-item field="formId" label="绑定表单">
          <a-select
            class="group-select"
            v-model="flowDef.formId"
            placeholder="选择表单"
            allow-search
            @change="formChange"
          >
            <a-option
              v-for="(form, fIdx) in forms"
              :key="fIdx"
              :value="form.id"
              :label="form.name"
            ></a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="remark" label="说明">
          <a-textarea v-model="flowDef.describe" :max-length="64" />
        </a-form-item>
        <a-form-item>
          <div style="clear: both"></div>
        </a-form-item>
      </a-form>
    </div>

    <flow-group-edit
      ref="groupModel"
      v-model:group="group"
      @ok="onSaveGroupCallback($event)"
    ></flow-group-edit>
  </section>
</template>

<script lang="ts" setup>
import { onBeforeMount, onMounted, ref, toRaw } from "vue";
import { useFlowStore, useOrganStore } from "@/stores/index";
import FlowIcon from "@/components/icons/FlowIcon.vue";
import FlowGroupEdit from "./flow-gorup-edit.vue";
import IconApi from "@/api/IconApi";
import { IconPlus } from "@arco-design/web-vue/es/icon";
// import { Icon } from "@arco-design/web-vue";
import FlowManApi from "@/api/FlowManApi";
// import { Sketch } from "@ckpack/vue-color";
import { WIDGET, EX } from "@/components/flow/common/FlowConstant";

const flowStore = useFlowStore();
let { flowDefinition, flowGroups, setPersonFields } = useFlowStore();

let groups = ref([]);
const loadGroups = () => {
  FlowManApi.listGroups({}).then((resp) => {
    if (resp.code == 0) {
      groups.value = resp.data.records || [];
    }
  });
  // groups.value = flowGroups;
};

// 选择分组
const groupChange = (key) => {
  console.log("groupChange", key);
  loadForms(key);
  const filterArr = groups.value.filter((group) => {
    return group.id == key;
  });
  flowDef.value.groupName = filterArr[0].name;
};

const forms = ref([]);
const loadForms = (groupId) => {
  FlowManApi.queryForms({ groupId }).then((resp) => {
    if (resp.code == 0) {
      forms.value = resp.data.records || [];
      if (flowDefinition.workFlowDef.id) {
        // 表单重新设置
        formChange(flowDefinition.workFlowDef.formId);
      }
      const list = forms.value?.filter((form) => {
        return form.id == flowDef.value.formId;
      });
      if (!list || list.length == 0) {
        flowDef.value.formId = "";
      }
    }
  });
};

// 选择表单后
const formChange = (id) => {
  console.log("formChange", id);
  if (!id) {
    return;
  }
  const findArr = toRaw(forms.value).filter((item, index) => {
    return item?.id === id;
  });
  const key = findArr[0]?.key;
  const name = findArr[0]?.name;
  const version = findArr[0]?.version;
  flowDef.value.formKey = key;
  flowDef.value.formName = name;
  flowDef.value.formVersion = version;
  console.log("formId", id);
  FlowManApi.getFormsById(id).then((resp) => {
    if (resp.code == 0) {
      const data = resp.data;
      console.log("personFields", data.formResource?.personFields);
      if (data.formResource?.personFields) {
        setPersonFields(data.formResource.personFields);
      }
      const fields = data.formResource.fields;
      console.log("fields", fields);

      const flowWidgets = factorial(fields);
      /* const flowWidgets = fields.map((field, index) => {
        return {
          name: field.field,
          type: EX[field.type] || field.type.toUpperCase(),
          label: field.label,
          required: isRequired(field.rules),
          id: field.id,
          details: field.children?.length > 0 ? field.children : null,
          options: field.componentProps?.options || [],
        };
      }); */
      flowDefinition.flowWidgets = flowWidgets;
      console.log("flowWidgets", flowWidgets);
      flowStore.setFlowDef(flowDefinition);
    }
  });
};
const factorial = (fields) => {
  return fields.map((field, index) => {
    return {
      name: field.field,
      type: EX[field.type] || field.type.toUpperCase(),
      label: field.label,
      required: isRequired(field.rules),
      id: field.id,
      details: field.children?.length > 0 ? factorial(field.children) : null,
      options: field.componentProps?.options || [],
    };
  });
};
// 判断是否必填
const isRequired = (rules = []) => {
  let flag = false;
  for (let i = 0; i < rules.length; i++) {
    const el = rules[i];
    if (el?.required) {
      flag = true;
      break;
    }
  }
  return flag;
};

function getLastSlashCharacter(str) {
  const lastSlashIndex = str.lastIndexOf("/");
  if (lastSlashIndex !== -1) {
    return str.slice(lastSlashIndex + 1);
  }
  return ""; // 如果没有斜杠，返回空字符串
}

let icons = ref([]);
const loadIcons = () => {
  /* IconApi.listSvgIcons().then((resp) => {
    icons.value = resp.data || [];
  }); */

  const imgList = import.meta.glob("@/assets/icons/*", {
    eager: true,
  });
  const imgKey: string[] = Object.keys(imgList);
  const arr: string[] = [];
  for (let i = 1; i < imgKey.length; i++) {
    arr.push(imgKey[i]);
  }
  icons.value = arr || [];
};

const onIconChoosed = (name) => {
  console.log("onIconChoosed", name);
  flowDef.value.icon = name;
};

// 当前的流程定义
let flowDef = ref({});
let rules = ref({
  icon: { required: true, message: "请选择流程图标" },
  name: { required: true, message: "请添加流程名称" },
  key: { required: true, message: "请设置该模型的唯一标识" },
  groupId: { required: true, message: "请选择流程分组" },
  formId: { required: true, message: "请选择绑定的表单" },
  flowAdminIds: {
    required: false,
    type: "array",
    message: "请选择流程管理员",
  },
});
let formRef = ref();
const validate = async () => {
  await formRef.value.validate((err) => {
    if (err) return;
  });
};

// 新增分组
let group = ref({});
let groupModel = ref();
const handleOpenAddGroup = () => groupModel.value.show();
const onSaveGroupCallback = (data) => {
  groups.value.push(data);
  flowDef.value.groupId = data.id; // 选择新添加的分组
};

// 流程管理员
let showChooseOrgan = ref(false);
const handleOpenChooseOrgan = () => (showChooseOrgan.value = true);

onMounted(() => {
  flowDef.value = flowDefinition.workFlowDef;
  if (flowDefinition.workFlowDef?.groupId) {
    loadForms(flowDefinition.workFlowDef?.groupId);
  }
});

onBeforeMount(() => {
  loadGroups();
  loadIcons();
});

defineExpose({
  validate,
});
</script>

<style lang="less">
.palette-select-box {
  .palette-tab {
    width: 100%;
    margin-bottom: 10px;

    .arco-radio-group-button {
      width: 100%;

      .arco-radio-button {
        flex: 1;
        text-align: center;
      }
    }
  }

  .palette-main {
    @FlowIconSize: 60px;

    display: grid;
    grid-template-columns: repeat(9, @FlowIconSize);
    grid-gap: 8px;

    .icon-item {
      border: 1px solid #d0d3d6;
      border-radius: var(--border-radius-large);
      cursor: pointer;
      width: @FlowIconSize;
      height: @FlowIconSize;
      display: flex;
      align-items: center;
      justify-content: center;

      img {
        overflow: hidden;
      }

      &:hover {
        border-color: #3370ff;
      }
    }
  }

  //   .fonts-box {
  //     width: 200px;
  //     margin-right: 10px;
  //     border-radius: 4px;

  //     .flowiconfont {
  //       margin: 4px;
  //       cursor: pointer;
  //       font-size: 24px;

  //       &:hover {
  //         border-radius: 4px;
  //         opacity: 0.8;
  //         box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.15), 0 8px 16px rgba(0, 0, 0, 0.15);
  //       }
  //     }
  //   }
}

.new-group-box {
  .arco-modal-body {
    padding-right: 40px;
  }
}
</style>

<style lang="less" scoped>
.fd-base-box {
  padding: 15px 0 10px;
  display: flex;
  justify-content: center;
  overflow-y: auto;
  height: 100%;

  .base-setting-panel {
    background-color: #fff;
    width: 600px;
    border-radius: var(--border-radius-large);
    display: flex;
    justify-content: center;
    padding: 24px 40px 0;
    height: 100%;
    overflow: hidden;
    overflow-y: auto;

    .group-box {
      display: flex;
      align-items: center;
      width: 100%;

      .group-select {
        flex: 1;
      }

      .new-group-btn {
        margin-left: 10px;
      }
    }

    .flow-admin-box {
      display: flex;
      gap: 4px;
      flex-wrap: wrap;
      margin-right: 4px;
    }

    .arco-btn {
      min-width: 32px;
    }
  }

  .icon-select-box {
    display: flex;
    flex-direction: row;
    align-items: center;

    .arco-link {
      margin-left: 10px;
    }
  }
}
</style>
